<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch">
      <el-form-item label="书名" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入书名"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="作者" prop="author">
        <el-input
          v-model="queryParams.author"
          placeholder="请输入作者"
          clearable
          style="width: 200px"
          @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="分类" prop="categoryId">
        <el-tree-select
          v-model="queryParams.categoryId"
          :data="categoryOptions"
          :props="{
            value: 'id',
            label: 'name',
            children: 'children'
          }"
          placeholder="请选择分类"
          clearable
          style="width: 200px"
          @change="handleQueryCategoryChange"
        />
      </el-form-item>
      <el-form-item label="上架状态" prop="publishStatus">
        <el-select v-model="queryParams.publishStatus" placeholder="上架状态" clearable style="width: 200px">
          <el-option
            v-for="dict in publishStatusOptions"
            :key="dict.value"
            :label="dict.label"
            :value="dict.value"
          />
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
        <el-button icon="Refresh" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="Plus"
          @click="handleAdd"
          v-hasPermi="['merchant:book:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="Edit"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['merchant:book:edit']"
        >修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="Delete"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['merchant:book:remove']"
        >删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-dropdown @command="handleBatchCommand" v-hasPermi="['merchant:book:edit']">
          <el-button type="info" plain>
            批量操作<el-icon class="el-icon--right"><arrow-down /></el-icon>
          </el-button>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="publish">批量上架</el-dropdown-item>
              <el-dropdown-item command="unpublish">批量下架</el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="warning"
          plain
          icon="Download"
          @click="handleExport"
          v-hasPermi="['merchant:book:export']"
        >导出</el-button>
      </el-col>
      <right-toolbar v-model="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="bookList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="书名" align="center" prop="name" />
      <el-table-column label="作者" align="center" prop="author" />
      <el-table-column label="分类" align="center" prop="categoryName" />
      <el-table-column label="封面" align="center" prop="pic" width="100">
        <template #default="scope">
          <el-image 
            style="width: 80px; height: 100px"
            :src="scope.row.pic"
            :preview-src-list="[scope.row.pic]">
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="定价" align="center" prop="price" />
      <el-table-column label="库存" align="center" prop="stock" />
      <el-table-column label="销量" align="center" prop="saleCount" />
      <el-table-column label="上架状态" align="center" prop="publishStatus">
        <template #default="scope">
          <el-switch
            v-model="scope.row.publishStatus"
            :active-value="1"
            :inactive-value="0"
            @change="handleStatusChange(scope.row)"
          />
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template #default="scope">
          <el-button
            link
            icon="View" 
            @click="handleView(scope.row)"
          >查看</el-button>
          <el-button
            link
            icon="Edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['merchant:book:edit']"
          >修改</el-button>
          <el-button
            link
            icon="Delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['merchant:book:remove']"
          >删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <pagination
      v-show="total>0"
      :total="total"
      v-model="queryParams.pageNum"
      :page-size="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改图书对话框 -->
    <el-dialog :title="title" v-model="open" width="800px" append-to-body>
      <el-form ref="bookRef" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="ISBN" prop="outProductId">
          <el-input v-model="form.outProductId" placeholder="请输入ISBN" />
        </el-form-item>
        <el-form-item label="书名" prop="name">
          <el-input v-model="form.name" placeholder="请输入书名" />
        </el-form-item>
        <el-form-item label="作者" prop="author">
          <el-input v-model="form.author" placeholder="请输入作者" />
        </el-form-item>
        <el-form-item label="分类" prop="categoryId">
          <el-tree-select
            v-model="form.categoryId"
            :data="categoryOptions"
            :props="{
              value: 'id',
              label: 'name',
              children: 'children'
            }"
            placeholder="请选择分类"
            clearable
            @change="handleCategoryChange"
          />
        </el-form-item>
        <el-form-item label="封面" prop="pic">
          <image-upload v-model="form.pic"/>
        </el-form-item>
        <el-form-item label="定价" prop="price">
          <el-input-number v-model="form.price" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="促销价" prop="promotionPrice">
          <el-input-number v-model="form.promotionPrice" :precision="2" :step="0.1" />
        </el-form-item>
        <el-form-item label="库存" prop="stock">
          <el-input-number v-model="form.stock" :min="0" />
        </el-form-item>
        <el-form-item label="出版社" prop="brandName">
          <el-input v-model="form.brandName" placeholder="请输入出版社" />
        </el-form-item>
        <el-form-item label="出版日期" prop="publishDate">
          <el-date-picker
            v-model="form.publishDate"
            type="date"
            placeholder="选择出版日期">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="页数" prop="pageNum">
          <el-input-number v-model="form.pageNum" :min="0" />
        </el-form-item>
        <el-form-item label="开本" prop="paperSize">
          <el-input v-model="form.paperSize" placeholder="请输入开本" />
        </el-form-item>
        <el-form-item label="纸张" prop="paperType">
          <el-input v-model="form.paperType" placeholder="请输入纸张" />
        </el-form-item>
        <el-form-item label="包装" prop="packaging">
          <el-input v-model="form.packaging" placeholder="请输入包装" />
        </el-form-item>
        <el-form-item label="上架状态" prop="publishStatus">
          <el-radio-group v-model="form.publishStatus">
            <el-radio
              v-for="dict in publishStatusOptions"
              :key="dict.value"
              :label="dict.value"
            >{{dict.label}}</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="简介" prop="description">
          <el-input v-model="form.description" type="textarea" placeholder="请输入内容" />
        </el-form-item>
      </el-form>
      <template #footer>
        <div class="dialog-footer">
          <el-button type="primary" @click="submitForm">确 定</el-button>
          <el-button @click="cancel">取 消</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 添加查看详情的对话框 -->
    <el-dialog 
      title="图书详情" 
      v-model="viewDialogVisible" 
      width="800px" 
      append-to-body
    >
      <el-descriptions :column="2" border>
        <el-descriptions-item label="ISBN">{{ viewForm.outProductId }}</el-descriptions-item>
        <el-descriptions-item label="书名">{{ viewForm.name }}</el-descriptions-item>
        <el-descriptions-item label="作者">{{ viewForm.author }}</el-descriptions-item>
        <el-descriptions-item label="分类">{{ viewForm.categoryName }}</el-descriptions-item>
        <el-descriptions-item label="封面" :span="2">
          <el-image 
            style="width: 120px; height: 150px"
            :src="viewForm.pic"
            :preview-src-list="[viewForm.pic]"
          />
        </el-descriptions-item>
        <el-descriptions-item label="定价">{{ viewForm.price }}</el-descriptions-item>
        <el-descriptions-item label="促销价">{{ viewForm.promotionPrice }}</el-descriptions-item>
        <el-descriptions-item label="库存">{{ viewForm.stock }}</el-descriptions-item>
        <el-descriptions-item label="销量">{{ viewForm.saleCount }}</el-descriptions-item>
        <el-descriptions-item label="出版社">{{ viewForm.brandName }}</el-descriptions-item>
        <el-descriptions-item label="出版日期">{{ viewForm.publishDate }}</el-descriptions-item>
        <el-descriptions-item label="页数">{{ viewForm.pageNum }}</el-descriptions-item>
        <el-descriptions-item label="开本">{{ viewForm.paperSize }}</el-descriptions-item>
        <el-descriptions-item label="纸张">{{ viewForm.paperType }}</el-descriptions-item>
        <el-descriptions-item label="包装">{{ viewForm.packaging }}</el-descriptions-item>
        <el-descriptions-item label="简介" :span="2">{{ viewForm.description }}</el-descriptions-item>
      </el-descriptions>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="viewDialogVisible = false">关 闭</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup name="Book">
import { listBook, getBook, delBook, addBook, updateBook, changeBookStatus, batchChangeBookStatus } from "@/api/merchant/book";
import { listCategory } from "@/api/merchant/category";
import ImageUpload from '@/components/ImageUpload/index.vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowDown } from '@element-plus/icons-vue'
import { ref, reactive, onMounted } from 'vue'

const { proxy } = getCurrentInstance();

const publishStatusOptions = ref([
  { label: "上架", value: 1 },
  { label: "下架", value: 0 }
]);

// 列表数据
const bookList = ref([]);
const categoryOptions = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const total = ref(0);
const title = ref("");
const categorySelectedIds = ref([]);

// 查询参数
const queryParams = ref({
  pageNum: 1,
  pageSize: 10,
  name: undefined,
  author: undefined,
  outProductId: undefined,
  categoryId: undefined,
  publishStatus: undefined
});

// 表单参数
const form = ref({
  id: undefined,
  outProductId: undefined,
  name: undefined,
  author: undefined,
  categoryId: undefined,
  pic: undefined,
  price: undefined,
  promotionPrice: undefined,
  stock: undefined,
  brandName: undefined,
  publishDate: undefined,
  pageNum: undefined,
  paperSize: undefined,
  paperType: undefined,
  packaging: undefined,
  publishStatus: 0,
  description: undefined
});

// 表单校验规则
const rules = {
  outProductId: [
    { required: true, message: "ISBN不能为空", trigger: "blur" }
  ],
  name: [
    { required: true, message: "书名不能为空", trigger: "blur" }
  ],
  author: [
    { required: true, message: "作者不能为空", trigger: "blur" }
  ],
  categoryId: [
    { required: true, message: "请选择分类", trigger: "change" }
  ],
  price: [
    { required: true, message: "定价不能为空", trigger: "blur" },
    { type: 'number', min: 0, message: "定价必须大于0", trigger: "blur" }
  ],
  stock: [
    { required: true, message: "库存不能为空", trigger: "blur" },
    { type: 'number', min: 0, message: "库存必须大于等于0", trigger: "blur" }
  ],
  brandName: [
    { required: true, message: "出版社不能为空", trigger: "blur" }
  ]
};

/** 查询图书列表 */
const getList = async () => {
  try {
    loading.value = true;
    const response = await listBook(queryParams.value);
    bookList.value = response.rows;
    total.value = response.total;
  } catch (error) {
    console.error('获取列表失败:', error);
  } finally {
    loading.value = false;
  }
};

/** 取按钮 */
const cancel = () => {
  open.value = false;
  reset();
};

/** 表单重置 */
const reset = () => {
  form.value = {
    id: undefined,
    outProductId: undefined,
    name: undefined,
    author: undefined,
    categoryId: undefined,
    pic: undefined,
    price: undefined,
    promotionPrice: undefined,
    stock: undefined,
    brandName: undefined,
    publishDate: undefined,
    pageNum: undefined,
    paperSize: undefined,
    paperType: undefined,
    packaging: undefined,
    publishStatus: 0,
    description: undefined
  };
  categorySelectedIds.value = [];
  proxy?.resetForm("bookRef");
};

/** 搜索按钮操作 */
const handleQuery = () => {
  queryParams.value.pageNum = 1;
  getList();
};

/** 重置按钮操作 */
const resetQuery = () => {
  proxy?.resetForm("queryRef");
  queryParams.value.pageNum = 1;
  handleQuery();
};

/** 新增按钮操作 */
const handleAdd = () => {
  reset();
  getCategoryOptions();
  open.value = true;
  title.value = "添加图书";
};

/** 修改按钮操作 */
const handleUpdate = async (row) => {
  reset();
  await getCategoryOptions();
  const bookId = row.id || ids.value[0];
  const response = await getBook(bookId);
  Object.assign(form.value, response.data);
  categorySelectedIds.value = [form.value.categoryId];
  open.value = true;
  title.value = "修改图书";
};

/** 获取分类选项 */
const getCategoryOptions = async () => {
  try {
    const response = await listCategory();
    if (response.rows && response.rows.length > 0) {
      // 处理树形结构
      categoryOptions.value = proxy.handleTree(response.rows, "id", "parentId");
    }
  } catch (error) {
    console.error('获取分类失败:', error);
    ElMessage.error('获取分类数据失败');
  }
};

/** 分类选择框变化 */
const handleQueryCategoryChange = (value) => {
  queryParams.value.categoryId = value;
  handleQuery(); // 选择后自动触发搜索
};

/** 分类选择框变化（表单中） */
const handleCategoryChange = (value) => {
  form.value.categoryId = value;
  // 获取分类名称
  const category = findCategoryById(categoryOptions.value, value);
  if (category) {
    form.value.categoryName = category.name;
  }
};

// 递归查找分类
const findCategoryById = (categories, id) => {
  for (const category of categories) {
    if (category.id === id) {
      return category;
    }
    if (category.children) {
      const found = findCategoryById(category.children, id);
      if (found) {
        return found;
      }
    }
  }
  return null;
};

/** 多选框选中数据 */
const handleSelectionChange = (selection) => {
  ids.value = selection.map(item => item.id);
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
};

// 批量操作处理
const handleBatchCommand = async (command) => {
  const selectedIds = ids.value;
  if (selectedIds.length === 0) {
    ElMessage.warning('请选择要操作的图书');
    return;
  }

  const statusMap = {
    'publish': 1,
    'unpublish': 0
  };

  const confirmMessage = command === 'publish' ? '确认要上架选中的图书吗？' : '确认要下架选中的图书吗？';
  
  try {
    await ElMessageBox.confirm(confirmMessage, '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    });
    
    await batchChangeBookStatus(selectedIds, statusMap[command]);
    ElMessage.success(command === 'publish' ? '批量上架成功' : '批量下架成功');
    getList();
  } catch (error) {
    console.error('批量操作失败:', error);
  }
};

// 状态修改处理
const handleStatusChange = async (row) => {
  const text = row.publishStatus === 1 ? "上架" : "下架";
  try {
    await ElMessageBox.confirm(
      `确认要${text}【${row.name}】吗？`,
      "提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await changeBookStatus(row.id, row.publishStatus);
    ElMessage.success(`${text}成功`);
  } catch (error) {
    row.publishStatus = row.publishStatus === 1 ? 0 : 1;
    console.error('状态修改失败:', error);
  }
};

// 表单提交
const submitForm = async () => {
  proxy.$refs["bookRef"].validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true;
        // 确保所有数值类型字段都是数字
        const submitData = {
          ...form.value,
          categoryId: form.value.categoryId ? Number(form.value.categoryId) : null,
          price: form.value.price ? Number(form.value.price) : null,
          promotionPrice: form.value.promotionPrice ? Number(form.value.promotionPrice) : null,
          stock: form.value.stock ? Number(form.value.stock) : null,
          pageNum: form.value.pageNum ? Number(form.value.pageNum) : null,
          publishStatus: form.value.publishStatus ? Number(form.value.publishStatus) : 0
        };

        if (form.value.id) {
          await updateBook(submitData);
          ElMessage.success("修改成功");
        } else {
          await addBook(submitData);
          ElMessage.success("新增成功");
        }
        open.value = false;
        getList();
      } catch (error) {
        console.error('提交失败:', error);
        ElMessage.error(error.message || '操作失败');
      } finally {
        loading.value = false;
      }
    }
  });
};

// 删除处理
const handleDelete = async (row) => {
  const bookIds = row.id || ids.value;
  const bookNames = row.name || bookList.value.filter(item => ids.value.includes(item.id)).map(item => item.name).join('、');
  
  try {
    await ElMessageBox.confirm(
      `是否确认删除图书【${bookNames}】？`,
      "警告",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }
    );
    await delBook(bookIds);
    getList();
    ElMessage.success("删除成功");
  } catch (error) {
    console.error('删除失败:', error);
  }
};

/** 导出按钮操作 */
const handleExport = () => {
  proxy.download('merchant/book/export', {
    ...queryParams.value
  }, `book_${new Date().getTime()}.xlsx`);
};

// 查看详情相关变量
const viewDialogVisible = ref(false)
const viewForm = ref({})

// 查看详情按钮操作
const handleView = async (row) => {
  try {
    loading.value = true
    const response = await getBook(row.id)
    if (response.code === 200) {
      viewForm.value = response.data
      viewDialogVisible.value = true
    } else {
      ElMessage.error(response.msg || '获取详情失败')
    }
  } catch (error) {
    console.error('获取详情失败:', error)
    ElMessage.error(error.message || '获取详情失败')
  } finally {
    loading.value = false
  }
}

onMounted(() => {
  getList();
  getCategoryOptions();
});
</script>
